package com.hui.utils;

import com.hui.vo.FilesUploadVo;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 李昭辉
 * @Date: 2021/08/31/10:39
 * @Description:
 */
@Component("fastDFSUtil")
public class FastDFSUtil {

    public List<FilesUploadVo> fastDfsUpload(List<Map<String, String>> messageList) throws Exception{
        // 返回结果
        List<FilesUploadVo> list = new ArrayList<>();
        // 获取 StorageClient1 客户端
        ClientGlobal.initByProperties("fastdfs-client.properties");
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        StorageServer storageServer = null;
        StorageClient1 client = new StorageClient1(trackerServer, storageServer);
        // 上传
        for (Map<String, String> map : messageList) {
            // 定义元信息
            NameValuePair[] nameValuePairs = new NameValuePair[1];
            nameValuePairs[0] = new NameValuePair("fileName", map.get("oldName"));
            // 上传到FastDfs服务器
            String dfsPath = client.upload_file1(map.get("path"), map.get("lastName"), nameValuePairs);
            // 上传成功后,把相关信息保存到list中
            list.add(new FilesUploadVo(dfsPath, map.get("oldName")));
        }
        // 关闭服务
        trackerServer.close();
        return list;
    }

}
